package teacher.action;

import java.io.FileOutputStream;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;

import teacher.actionform.HomeworkForm;
import util.Encoding;
import dao.HomeworkMagDao;
import dao.impl.HomeworkMagImpl;
import domain.Homework;
import domain.Teacher;

/**
 * 
 * Jun 4, 2009
 *
 * @author Fabian
 *
 */
public class ManagerHomeworkAction extends DispatchAction {
	
	/**
	 * 浏览所有作业的Action，但是要传递分页参数（start--开始，limit--间隔）
	 */
	public ActionForward show(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Teacher tch = (Teacher)request.getSession().getAttribute("user");
		int tch_id = tch.getId();
		
		String flag = request.getParameter("flag");
		
		HomeworkForm hf = (HomeworkForm)form;
		
		int start = hf.getStart();
		int limit = hf.getLimit();	
		
		List<Homework> list = null;
		int totalCount = 0;
		
		HomeworkMagDao hmd = new HomeworkMagImpl();
		
		String resultArray = "";
		
		if ("book".equals(flag)) {
			list = hmd.getPageBookHomework(start, limit, tch_id);
			totalCount = hmd.getBookTotalCount(tch_id);			
			
			for (Iterator<Homework> it = list.iterator(); it.hasNext(); ) {
				Homework h = it.next();
				Date pub_time = h.getPub_time();
				Date sub_time = h.getSub_time();				
				long p = pub_time.getTime();
				long e = sub_time.getTime();
				
				Date now = new Date();
				long now_l = now.getTime();
				
				String status = "进行中...";
				if (now_l > e) {
					status = "已经过期";
				}
				
				resultArray = resultArray + "{id: " + h.getId() + ", status: '" + status + "', title:'" + h.getTitle() + "', content:'" + h.getContent() + 
											"', pub_user:'" + h.getPub_user() + "', pub_time: new Date(" + p + "), sub_time: new Date(" + e + "), grade: '" + 
											h.getGrade() + " 级', banji: '" + h.getBanji() + " 班', need_count:" + h.getNeed_count() + ", sub_count:" + 
											h.getSub_count() + ", correct_count:" + h.getCorrect_count() + "}";
				if (it.hasNext()) {
					resultArray = resultArray + ",";
				}			
			}
		} else if ("good".equals(flag)) {
			list = hmd.getPageGoodHomework(start, limit, tch_id);
			totalCount = hmd.getGoodTotalCount(tch_id);			
			
			for (Iterator<Homework> it = list.iterator(); it.hasNext(); ) {
				
				Homework h = it.next();
				
				Date pub_time = h.getPub_time();
				Date sub_time = h.getSub_time();				
				long p = pub_time.getTime();
				long e = sub_time.getTime();
				
				Date now = new Date();
				long now_l = now.getTime();
				
				String status = "进行中...";
				if (now_l > e) {
					status = "已经过期";
				}			
				
				if ("swf".equals(h.getFormat())) {
					resultArray = resultArray + "{id: " + h.getId() + ", status: '" + status + "', title:'" + h.getTitle() + "', content:'" + h.getContent() + "', format: '" + h.getFormat() + 
											"',size: '" + h.getSize() + "', pub_user:'" + h.getPub_user() + "', pub_time: new Date(" + p + "), sub_time: new Date(" + e + "), grade: '" + 
											h.getGrade() + " 级', banji: '" + h.getBanji() + " 班', need_count:" + h.getNeed_count() + ", sub_count:" + 
											h.getSub_count() + ", correct_count:" + h.getCorrect_count() + ", operate: '" +
											"<a href=\"jsp/tch/see_online.jsp?id=" + h.getId() + "&path=" + h.getPath() + "\" target=\"_blank\"><img src=\"images/main/book_open.png\" alt=\"在线浏览\"/></a>" + 
											"&nbsp;&nbsp;&nbsp;&nbsp;" +
											"<a href=\"jsp/tch/download.jsp?path=" + h.getPath() + "\" target=\"_blank\"><img src=\"images/main/download.png\" alt=\"下载\"/></a>'}";
				} else {
					resultArray = resultArray + "{id: " + h.getId() + ", status: '" + status + "', title:'" + h.getTitle() + "', content:'" + h.getContent() + "', format: '" + h.getFormat() + 
											"',size: '" + h.getSize() + "', pub_user:'" + h.getPub_user() + "', pub_time: new Date(" + p + "), sub_time: new Date(" + e + "), grade: '" + 
											h.getGrade() + " 级', banji: '" + h.getBanji() + " 班', need_count:" + h.getNeed_count() + ", sub_count:" + 
											h.getSub_count() + ", correct_count:" + h.getCorrect_count() + ", operate: '" +
											"<a href=\"jsp/tch/download.jsp?path=" + h.getPath() + "\" target=\"_blank\"><img src=\"images/main/download.png\" alt=\"下载\"/></a>'}";
				}
				if (it.hasNext()) {
					resultArray = resultArray + ",";
				}			
			}
		}
		
		
		
		String jsonStr = "";
		jsonStr = "{totalProperty: " + totalCount + ", root: [ " + resultArray + " ]}";
		
		request.setAttribute("result", jsonStr);
				
		return mapping.findForward("show_result");
	}
	/**
	 * 添加作业
	 */
	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		Teacher tch = (Teacher)request.getSession().getAttribute("user");
		String pub_user = tch.getName();
		
		String flag = request.getParameter("flag");
		
		HomeworkForm hf = (HomeworkForm)form;
		
		boolean result = false;
		
		if ("book".equals(flag)) {
			
			String title = hf.getTitle();
			String sub_time = hf.getSub_time();		
			String grade = hf.getGrade();
			String banji = hf.getBanji();
			String content = hf.getContent();
			
			Homework hw = new Homework();
			hw.setTitle(title);
			hw.setContent(content);
			hw.setSort("bookHomework");
			hw.setPub_user(pub_user);
			SimpleDateFormat sdf = new SimpleDateFormat("yy年MM月dd日");
			hw.setSub_time(sdf.parse(sub_time));
			hw.setGrade(grade);
			hw.setBanji(banji);
			
			HomeworkMagDao hmd = new HomeworkMagImpl();
			result = hmd.addBookHomework(hw);
			
		} else if ("good".equals(flag)) {
			
			String title = URLDecoder.decode(hf.getTitle(), "utf-8");
			String content = URLDecoder.decode(hf.getContent(), "utf-8");
			String sub_time = URLDecoder.decode(hf.getSub_time(), "utf-8");
			FormFile file = hf.getFile_path();
			String grade = hf.getGrade();
			String banji = hf.getBanji();
			
			if (file != null) {
				
				//设置文件名				
				String dir = servlet.getServletContext().getRealPath("/");
				String fileName = Encoding.gbkToUTF(file.getFileName());		//解决乱码问题
				//获取扩展名
				String format = fileName.substring((fileName.lastIndexOf('.') + 1));
				if (format.length() > 4) {
					format = fileName.substring(fileName.length()-3);
				}
				//给file一个新的名字，使用UUID
				String newfileName = UUID.randomUUID().toString() + "." + format;
				
				String size = "";
				int theSize = file.getFileSize();
				int fileSize = 0;
				if (theSize > 1024) {
					fileSize = (theSize)/1024;
					size = fileSize + " KB";
				} else {
					fileSize = theSize;
					size = fileSize + " B";
				}
				
				FileOutputStream fos = new FileOutputStream(dir + "resource/homework/" + newfileName);
				fos.write(file.getFileData());
				fos.flush();
				fos.close();
				
				
				String filePath = "resource/homework/" + newfileName;
				
				
				//更新数据库
				Homework hw = new Homework();
				hw.setTitle(title);
				hw.setContent(content);
				hw.setFormat(format);
				hw.setSort("goodHomework");
				hw.setPath(filePath);
				hw.setSize(size);				
				hw.setPub_user(pub_user);				
				SimpleDateFormat sdf = new SimpleDateFormat("yy年MM月dd日");
				hw.setSub_time(sdf.parse(sub_time));
				hw.setGrade(grade);
				hw.setBanji(banji);
				
				HomeworkMagDao hmd = new HomeworkMagImpl();
				result = hmd.addGoodHomework(hw);
				
			}			
			
		}
		
		//组装返回的JSON数据
		String returnStr = "";
		if (result) {
			
			returnStr = "{success: true, msg: '恭喜，布置作业成功！'}";
			request.setAttribute("result", returnStr);
			
		} else {
			
			returnStr = "{failure: true, msg: '抱歉，布置作业失败！请重新尝试！'}";
			request.setAttribute("result", returnStr);
			
		}		
		
		return mapping.findForward("add_result");
	}
	
	/**
	 * 修改更新作业数据
	 */
	public ActionForward modify(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		HomeworkForm hf = (HomeworkForm)form;
		
		Homework hw = new Homework();
		
		hw.setId(hf.getId());
		hw.setTitle(hf.getTitle());
		hw.setContent(hf.getContent());
		SimpleDateFormat sdf = new SimpleDateFormat("yy年MM月dd日");
		hw.setSub_time(sdf.parse(hf.getSub_time()));
		hw.setGrade(hf.getGrade());
		hw.setBanji(hf.getBanji());
		
		HomeworkMagDao hmd = new HomeworkMagImpl();
		boolean result = hmd.modifyHomework(hw);
		
		//组装返回的JSON数据
		String returnStr = "";
		if (result) {
			
			returnStr = "{success: true, msg: '恭喜，修改作业信息成功！'}";
			request.setAttribute("result", returnStr);
			
		} else {
			
			returnStr = "{failure: true, msg: '抱歉，修改作业信息失败！请重新尝试！'}";
			request.setAttribute("result", returnStr);
			
		}		
		return mapping.findForward("modify_result");
	}
	
	/**
	 * 删除作业
	 */
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		HomeworkForm hf = (HomeworkForm)form;
		int del_id = hf.getId();
		
		HomeworkMagDao hmd = new HomeworkMagImpl();
		boolean result = hmd.delHomework(del_id);
			
		//组装返回的JSON数据
		String returnStr = "";
		if (result) {
			
			returnStr = "{result: 'success', msg: '恭喜，删除作业成功！'}";
			request.setAttribute("result", returnStr);
			
		} else {
			
			returnStr = "{result: 'failure', msg: '抱歉，删除作业失败！请重新尝试！'}";
			request.setAttribute("result", returnStr);
			
		}		
		
		return mapping.findForward("del_result");
	}
}
